package org.lq.sm.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.lq.sm.dao.DictionaryDao;
import org.lq.sm.entity.Dictionary;
import org.lq.sm.util.Instantiation;
import org.lq.sm.util.JDBCUtil;
/**
 *  	字典数据访问实现类
 *@author  黄兴栋
 *@time  2020年8月9日
 *@package  org.lq.sm.dao.impl
 *
 */
public class DictionaryDaoImpl implements DictionaryDao {

	/**
	 * 添加
	 */
	@Override
	public int save(Dictionary t) {
		int num = 0;
		String sql = "insert into dictionary(name,typeid) values(?,?)";
		try {
			num = JDBCUtil.executeUpdate(sql, t.getName(),t.getTypeid());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return num;
	}

	/**
	 * 修改
	 */
	@Override
	public int update(Dictionary t) {
		int num = 0;
		String sql = "update dictionary set name = ?,typeid = ? where id = ?";
		try {
			num = JDBCUtil.executeUpdate(sql, t.getName(),t.getTypeid(),t.getId());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return num;
	}

	/**
	 * 删除
	 */
	@Override
	public int delete(int id) {
		int num = 0;
		String sql = "delete from dictionary where id = ?";
		try {
			num = JDBCUtil.executeUpdate(sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return num;
	}

	/**
	 * 查询所有
	 */
	@Override
	public List<Dictionary> findAll() {
		List<Dictionary> list = new ArrayList<>();
		String sql = "select * from dictionary";
		try {
			list = JDBCUtil.executeQuery(sql, new Instantiation<Dictionary>() {

				@Override
				public Dictionary instance(ResultSet rs) {
					Dictionary dic = new Dictionary();
					try {
						dic.setId(rs.getInt("id"));
						dic.setName(rs.getString("name"));
						dic.setTypeid(rs.getInt("typeid"));
					} catch (SQLException e) {
						e.printStackTrace();
					}
					return dic;
				}
			});
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 根据id查询
	 */
	@Override
	public Dictionary getById(int id) {
		List<Dictionary> list = new ArrayList<>();
		String sql = "select * from dictionary where id = ?";
		try {
			list = JDBCUtil.executeQuery(sql, new Instantiation<Dictionary>() {

				@Override
				public Dictionary instance(ResultSet rs) {
					Dictionary dic = new Dictionary();
					try {
						dic.setId(rs.getInt("id"));
						dic.setName(rs.getString("name"));
						dic.setTypeid(rs.getInt("typeid"));
					} catch (SQLException e) {
						e.printStackTrace();
					}
					return dic;
				}
			},id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list.get(0);
	}

}
